package org.sgx.gapigui.client.ui.extra.sjcl;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.core.client.ScriptInjector.FromUrl;
/**
 * GWT class that let you load and use the base methods of 
 * Stanford Javascript Crypto Library - http://crypto.stanford.edu/sjcl/. Usage: 
 * 
<pre>StanfordCryptoLib.load(new Callback<Void, Exception>() {			
	@Override
	public void onSuccess(Void result) {
		//ready to work
		String password = "banana4", plainText="En algún lugar de la mancha"; 
		String encrypted = StanfordCryptoLib.encrypt(password, plainText); 
		String decrypted = StanfordCryptoLib.decrypt(password, encrypted); 
	}			
	@Override
	public void onFailure(Exception reason) {
		Window.alert("Couldn't load the Crypto Library from http://crypto.stanford.edu/sjcl/"); 
	}
}); </pre> 
 * @author sg
 *
 */
public class StanfordCryptoLib {
	
	/**
	 * loads the JavaScript of the library from given url
	 * @param url
	 * @param callback
	 */
	public static void load(String url, final Callback<Void, Exception> callback) {
		FromUrl injector = ScriptInjector.fromUrl(url);		
		injector.setCallback(callback).setWindow(ScriptInjector.TOP_WINDOW).inject(); 
	}
	/**
	 * loads the JavaScript of the library from default location ("http://crypto.stanford.edu/sjcl/sjcl.js"). 
	 * @param callback
	 */
	public static void load(final Callback<Void, Exception> callback) {
		FromUrl injector = ScriptInjector.fromUrl("http://crypto.stanford.edu/sjcl/sjcl.js");		
		injector.setCallback(callback).setWindow(ScriptInjector.TOP_WINDOW).inject(); 
	}
	
	/**
	 * Simple decryption function. 
	 * @param password The password or key.
	 * @param ciphertext The ciphertext to decrypt.
	 * @return
	 */
	public static final native String decrypt(String password, String ciphertext)/*-{
		return $wnd.sjcl.decrypt(password, ciphertext); 
	}-*/;
	
	/**
	 * Simple encryption function. 
	 * @param password The password or key.
	 * @param plainText The data to encrypt.
	 * @return
	 */
	public static final native String encrypt(String password, String plainText)/*-{
		return $wnd.sjcl.encrypt(password, plainText); 
	}-*/;
	
}
